package com.bt.lms.ui.action.school_education.archives.basicMes;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.StuStatusBizTypeConstant;
import com.bt.lms.entity.StuStatusBasicInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.vo.school_education.stu_status.StuStatusBasicInfoVo;

import com.bt.lms.network.msg.packet.ReqMsgPacket;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import org.apache.commons.beanutils.BeanUtils;

import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;

/**
 * 学籍基本信息的编辑验证事件
 */
public class EditScrollVerify implements EventHandler {

    private VBox vBox;

    public EditScrollVerify(VBox totalVBox) {
        this.vBox = totalVBox;
    }

    @Override
    public void handle(Event event) {
        //1.获取用户输入
        StuStatusBasicInfoVo stuStatusBasicInfoVo = getInput();
        //2，验证用户输入
        String verifyMsg = getVerifyMsg(stuStatusBasicInfoVo);
        //3，组包
        byte[] bytes = null;
        if (verifyMsg == null){
            bytes = enCode(stuStatusBasicInfoVo);
        }
        //4.组网
        Socket socket = getNet();
        //5，发送消息
        boolean flag = sendMsg(socket, bytes);


    }

    /**
     * 验证用户输入是否合法
     * @param stuStatusBasicInfoVo vo对象
     * @return 验证消息
     */
    private String getVerifyMsg(StuStatusBasicInfoVo stuStatusBasicInfoVo) {
        String msg = "";

        String stuNo = stuStatusBasicInfoVo.getStuNo();
        if (stuNo.equals("")){
            msg += "学员编号为必填\r\n";
        }else {
            if (stuNo.length()>32){
                msg += "学员编号在0-32位之间\r\n";
            }
        }

        String name = stuStatusBasicInfoVo.getName();
        if (name.equals("")){
            msg += "姓名为必填\r\n";
        }else {
            if (stuNo.length()>24){
                msg += "姓名在0-24位之间\r\n";
            }
        }

        String idType = stuStatusBasicInfoVo.getiDType();
        if (idType.equals("")){
            msg += "证件类型为必填\r\n";
        }

        String idCard = stuStatusBasicInfoVo.getiDCard();
        if (idCard.equals("")){
            msg += "证件号码为必填\r\n";
        }else {
            if (idType.equals("身份证")){
            if (idCard.length()!= 18){
                msg += "证件号码必须为18位\r\n";
            }
            }
        }

        if (stuStatusBasicInfoVo.getEnterSchoolTime() == null){
            msg += "入学年月为必填\r\n";
        }

        String lengthOfSchooling = stuStatusBasicInfoVo.getLengthOfSchooling();
        if (lengthOfSchooling.equals("")){
            msg += "学制为必填\r\n";
        }else {
            if (lengthOfSchooling.length() > 24){
                msg += "学制在0-24位之间\r\n";
            }
        }

        String className = stuStatusBasicInfoVo.getClassName();
        if (className.equals("")){
            msg += "班级名称为必填\r\n";
        }else {
            if (className.length() > 24){
                msg += "班级名称在0-24位之间\r\n";
            }
        }

        String enpName = stuStatusBasicInfoVo.getEnrollPlan();
        if (enpName.equals("")){
            msg += "招生计划为必填\r\n";
        }else {
            if (enpName.length()>24){
                msg += "招生计划在0-24位之间\r\n";
            }
        }

        String learningCenter = stuStatusBasicInfoVo.getLearningCenter();
        if (learningCenter.equals("")){
            msg += "学习中心为必填\r\n";
        }else {
            if (learningCenter.length() > 24){
                msg += "学习中心在0-24位之间\r\n";
            }
        }

        String specialty = stuStatusBasicInfoVo.getSpecialty();
        if (specialty.equals("")){
            msg += "专业为必填\r\n";
        }else {
            if (specialty.length() > 24){
                msg += "专业在0-24位之间\r\n";
            }
        }

        Integer currentState = stuStatusBasicInfoVo.getCurrentState();
        if (currentState == null){
            msg += "学生当前状态为必填\r\n";
        }

        if (!(msg.equals(""))){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
            alert.show();
        }

        if (msg.equals("")){
            msg = null;
        }
        return msg;
    }

    /**
     * 获取用户输入
     *
     * @return vo对象
     */
    private StuStatusBasicInfoVo getInput() {
        StuStatusBasicInfoVo stuStatusBasicInfoVo = new StuStatusBasicInfoVo();

        TextField stuNoTF = (TextField) this.vBox.lookup("#stuNoTF");
        String stuNoTFStr = stuNoTF.getText().trim();
        stuStatusBasicInfoVo.setStuNo(stuNoTFStr);

        TextField nameTF = (TextField) this.vBox.lookup("#nameTF");
        String nameTFStr = nameTF.getText().trim();
        stuStatusBasicInfoVo.setName(nameTFStr);

        ComboBox iDTypeTF = (ComboBox) this.vBox.lookup("#iDTypeTF");
        String iDTypeTFValue = (String) iDTypeTF.getValue();
        stuStatusBasicInfoVo.setiDType(iDTypeTFValue);

        DatePicker enterSchoolTimeTF = (DatePicker) this.vBox.lookup("#enterSchoolTimeTF");
        if (enterSchoolTimeTF.getValue() != null){
            String enterSchoolTimeTFStr = enterSchoolTimeTF.getValue().toString();
            stuStatusBasicInfoVo.setEnterSchoolTime(LocalDate.parse(enterSchoolTimeTFStr));
        }
        TextField iDCardDP = (TextField) this.vBox.lookup("#iDCardDP");
        String iDCardDPStr = iDCardDP.getText().trim();
        stuStatusBasicInfoVo.setiDCard(iDCardDPStr);

        TextField classNameTF = (TextField) this.vBox.lookup("#classNameTF");
        String classNameTFStr = classNameTF.getText().trim();
        stuStatusBasicInfoVo.setClassName(classNameTFStr);

        TextField lengthOfSchoolingTF = (TextField) this.vBox.lookup("#lengthOfSchoolingTF");
        String lengthOfSchoolingTFStr = lengthOfSchoolingTF.getText().trim();
        stuStatusBasicInfoVo.setLengthOfSchooling(lengthOfSchoolingTFStr);

        TextField studyCenterTF = (TextField) this.vBox.lookup("#studyCenterTF");
        String studyCenterTFStr = studyCenterTF.getText().trim();
        stuStatusBasicInfoVo.setLearningCenter(studyCenterTFStr);

        TextField enrollPlanTF = (TextField) this.vBox.lookup("#enrollPlanTF");
        String enrollPlanTFStr = enrollPlanTF.getText().trim();
        stuStatusBasicInfoVo.setEnrollPlan(enrollPlanTFStr);

        TextField specialtyTF = (TextField) this.vBox.lookup("#specialtyTF");
        String specialtyTFStr = specialtyTF.getText().trim();
        stuStatusBasicInfoVo.setSpecialty(specialtyTFStr);

        ComboBox currentStateCB = (ComboBox) this.vBox.lookup("#currentStateCB");
        String cbValue = (String) currentStateCB.getValue();
        int leave = -1;
        switch (cbValue){
            case "在籍":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_Be_REGISTERED;
                break;
            case "未注册":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_UNREGISTERED;
                break;
            case "转出":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_ROLLOUT;
                break;
            case "休学":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_TEMPORARY_ABSENCE_FROM_SCHOOL;
                break;
            case "退学":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_DROP_OUT;
                break;
            case "开除":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_EXPEL;
                break;
            case "毕业":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_GRADUATE;
                break;
            case "异动中":
                leave = BOConstant.STU_STATUS_BASIC_INFO_CURRENT_STATE_TRANSACTIONED;
                break;
        }
        stuStatusBasicInfoVo.setCurrentState(leave);

        return stuStatusBasicInfoVo;
    }

    /**
     * 5.发送消息
     *
     * @param socket 网
     * @param bytes  消息包
     * @return 是否成功
     */
    private boolean sendMsg(Socket socket, byte[] bytes) {
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //接收响应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf);

            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();
            if (data != null){
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText("保存成功");
                alert.showAndWait();
            }
            //界面回显


            //关闭资源
            out.close();
            socket.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 4.获取网络
     *
     * @return 网
     */
    private Socket getNet() {
        String ip = "127.0.0.1";
        int port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return socket;
    }

    /**
     * 3.组包
     *
     * @param stuStatusBasicInfoVo 学籍基本信息
     * @return
     */
    private byte[] enCode(StuStatusBasicInfoVo stuStatusBasicInfoVo) {

        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(StuStatusBizTypeConstant.STU_STATUS_BASIC_INFO_BIZ_TYPE_EDIT);
        StuStatusBasicInfo stuStatusBasicInfo = new StuStatusBasicInfo();

        try {
            BeanUtils.copyProperties(stuStatusBasicInfo, stuStatusBasicInfoVo);
            stuStatusBasicInfo.setId(1L);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        String stuStatusStr = JSON.toJSONString(stuStatusBasicInfo);
        reqMsg.setData(stuStatusStr);

        return reqMsg.toBytes();
    }
}
